package dao;

import domin.Role;
import util.CommonDao;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.TreeSet;

public final class RoleDao {
    private static RoleDao roleDao = null;
    private RoleDao() {
    }
    public static RoleDao getInstance() {
        if (roleDao == null) {
            roleDao = new RoleDao();
        }
        return roleDao;
    }

    public Role find(Connection connection, Integer id) throws SQLException {
        //创建Role类型的引用，暂不创建对象
        Role desiredRole = null;
        String sql_select_id = "SELECT * FROM role WHERE id = ?";
        PreparedStatement pstmt_select_id = connection.prepareStatement(sql_select_id);
        pstmt_select_id.setInt(1, id);
        ResultSet resultSet_select_id = pstmt_select_id.executeQuery();
        if (resultSet_select_id.next()) {
            String role = resultSet_select_id.getString("role");
            desiredRole = new Role(id, role);
        }
        JdbcHelper.close(resultSet_select_id, pstmt_select_id);
        return desiredRole;
    }

    public Collection<Role> findAll(Connection connection, Pagination pagination, List<Condition> conditionList)
            throws SQLException {
        Collection<Role> desiredRoles = new TreeSet<Role>();
        StringBuilder sql_select = new StringBuilder("SELECT * FROM role ");
        if (conditionList != null) {
            String whereClause = Condition.toWhereClause(conditionList.toString());
            sql_select.append(whereClause);
        }
        int totalNum = CommonDao.getInstance().count(connection, "role");
        if (pagination != null) {
            String paginationClause = pagination.toLimitClause(totalNum);
            sql_select.append(paginationClause);
        }
        PreparedStatement pstmt_select_all =
                connection.prepareStatement(sql_select.toString());
        ResultSet resultSet = pstmt_select_all.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String role = resultSet.getString("role");
            Role desiredRole = new Role(id, role);
            desiredRoles.add(desiredRole);
        }
        JdbcHelper.close(resultSet, pstmt_select_all);
        return desiredRoles;
    }

}
